package com.wavehi.web.homework.seventh;

import com.wavehi.pojo.Human;
import com.wavehi.service.HumanService;
import com.wavehi.web.BaseServlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author WaveHi
 * @Date 18/9/2021 上午 10:46
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
@WebServlet(urlPatterns = "/humanServlet", loadOnStartup = 1)
public class HumanServlet extends BaseServlet {
    //获取service层对象
    private HumanService hService = new HumanService();

    /**
     * 尽为开发效率而保留的方法，无实际意义
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void base(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    /**
     * 获取所有人员信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取实体信息
        List<Human> humans = hService.list();
        //设置域对象的数据
        req.getSession().setAttribute("humans", humans);
        //获取请求转发对象
        RequestDispatcher dis = req.getRequestDispatcher("page/homework/humanManage.jsp");
        //转发
        dis.forward(req, resp);
    }

    /**
     * 添加成员
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一字符集
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("UTF-8");
        //获取域对象的数据
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        Human human = new Human(name, Integer.valueOf(age.trim()));
        //设置回显数据
        req.setAttribute("name", name);
        req.setAttribute("age", age.trim());
        //添加信息
        hService.add(human);
        //获取请求转发对象
        RequestDispatcher dis = req.getRequestDispatcher("humanServlet?action=list");
        //转发
        dis.forward(req, resp);
    }
}
